package com.ellecity06.cwhiskymall.ui.address.add

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.bean.request.AddressAddRequest
import com.ellecity06.cwhiskymall.databinding.ActivityAddressAddBinding
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity

/**
 * @author ellecity06
 * @time 2024/10/31 13:46
 * @des
 */
class AddressAddActivity : BaseMvvmActivity<ActivityAddressAddBinding, AddressAddViewModel>(),
    View.OnClickListener, OnAddressPickedListener {

    private val addressId: Int by lazy { intent.getIntExtra("address_id", -1) }
    override fun inflateBinding(): ActivityAddressAddBinding {
        return ActivityAddressAddBinding.inflate(layoutInflater)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        title = "新增收货地址"
        fetchAddress()
    }

    override fun initEvent() {
        binding.tvChooseCity.keyListener = null
        binding.tvChooseCity.setOnClickListener(this)
        binding.tvAdd.setOnClickListener(this)
    }

    private fun fetchAddress() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(AddressAddIntent.FetchAddress(addressId))
        }
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is AddressAddState.AddSuccess -> {
                    setResult(RESULT_OK)
                    finish()
                }
                is AddressAddState.FetchAddressSuccess -> {
                    setAddressInfo(it.data)
                }
            }
        }
    }

    private fun setAddressInfo(data: AddressAddRequest) {
        binding.etName.setText(data.memberName)
        binding.etPhone.setText(data.telMobile)
        binding.tvChooseCity.setText(data.addressAll)
        binding.etAddress.setText(data.detailAddress)
        binding.sw.isChecked = data.isDefault == 1

    }

    override fun onClick(view: View) {
        when (view.id) {
            binding.tvChooseCity.id -> {
                chooseCity()
            }
            binding.tvAdd.id -> {
                addressAdd()
            }
        }
    }

    private fun addressAdd() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(
                AddressAddIntent.AddAddress(
                    addressId,
                    binding.etName.text.toString().trim(),
                    binding.etPhone.text.toString().trim(),
                    binding.tvChooseCity.text.toString().trim(),
                    binding.etAddress.text.toString().trim(),
                    binding.sw.isChecked
                )
            )
        }
    }

    private fun chooseCity() {
        val picker = AddressPicker(this)
        picker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
        picker.setOnAddressPickedListener(this)
        picker.wheelLayout.setOnLinkageSelectedListener { first, second, third ->
            picker.titleView.text = String.format(
                "%s%s%s",
                picker.firstWheelView.formatItem(first),
                picker.secondWheelView.formatItem(second),
                picker.thirdWheelView.formatItem(third)
            )
        }
        picker.show()
    }

    override fun onAddressPicked(
        province: ProvinceEntity?,
        city: CityEntity?,
        county: CountyEntity?
    ) {
        if (province == null || city == null || county == null) {
            ToastUtils.show("地区选取失败，请重新选择")
            binding.tvChooseCity.setText("")
            return
        }
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(AddressAddIntent.ChooseCity(province, city, county))
        }
        logD("province=${province.code}")
        binding.tvChooseCity.setText("${province?.name} ${city?.name} ${county?.name}")
    }
}